package club.haomoon.boss.helper;


import club.haomoon.core.config.AlipayConfig;
import club.haomoon.core.entity.system.RechargeOrderData;
import club.haomoon.core.mapper.system.RechargeOrderMapper;
import club.haomoon.core.util.ConfigUtil;
import club.haomoon.core.util.PropertyUtil;
import club.haomoon.core.util.StringUtils;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.springframework.stereotype.Component;
/**
 * -------------------------
 * @Description: 支付宝助手类
 * @Author: Wangjianwei
 * @Date: 2025/02/19 11:09
 * -------------------------
 */
@Component
public class AlipayHelper {

    /**
     * 支付宝退款
     * @param rechargeOrder
     * @param refundSn
     */
    public String aliPayRefund(RechargeOrderData rechargeOrder, String refundSn, RechargeOrderMapper rechargeOrderMapper) throws Exception {
        String gateWay = StringUtils.isNotNull(PropertyUtil.get("cms.alidebug")) && PropertyUtil.get("cms.alidebug").equals("true") ? AlipayConfig.GATEWAY_URL_DEBUG : AlipayConfig.GATEWAY_URL;
        AlipayClient alipayClient = new DefaultAlipayClient(gateWay, ConfigUtil.getAliDevPay("app_id"), ConfigUtil.getAliDevPay("private_key"), "json", AlipayConfig.CHARSET, ConfigUtil.getAliDevPay("ali_public_key"), AlipayConfig.SIGN_TYPE);
        AlipayTradeRefundRequest aliRequest = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel alipayTradeRefundModel = new AlipayTradeRefundModel();
        alipayTradeRefundModel.setTradeNo(rechargeOrder.getTransactionId());
        alipayTradeRefundModel.setRefundAmount(rechargeOrder.getOrderAmount().toString());
        alipayTradeRefundModel.setOutRequestNo(rechargeOrder.getSn());
        aliRequest.setBizModel(alipayTradeRefundModel);
        AlipayTradeRefundResponse response = alipayClient.execute(aliRequest);
        if(response.isSuccess()) {
            String ret = JSONObject.toJSONString(response);
            if (StringUtils.isNotNull(ret)) {
                JSONObject refundResponseJSON = JSONObject.parseObject(ret);
                rechargeOrder.setRefundTransactionId(refundResponseJSON.getBigInteger("tradeNo"));
                rechargeOrderMapper.updateById(rechargeOrder);
            }
            return ret;
        } else {
            throw new Exception(response.getBody());
        }
    }
}
